//
//  EFSearchViewController.m
//  EnjogFood
//
//  Created by 张文瀚 on 2017/5/1.
//  Copyright © 2017年 wf. All rights reserved.
//

#import "EFSearchViewController.h"
#import "EFShoppingCartItem.h"
#import "EFSearchRecentView.h"
#import "EFSearchResultItem.h"
#import "EFSearchTopCell.h"
#import "EFSearchItem.h"
#import "EFSearchResultCell.h"
#import "EFRecentSearchItem.h"
#import "EFTopTypeCell.h"
#import "EFSearchCategoryItem.h"
#import "iToast.h"
#import "EFGoodsDetailViewController.h"
#import "EFSepecialItem.h"

@interface EFSearchViewController ()<UITableViewDelegate, UITableViewDataSource,UITextFieldDelegate>
@property(nonatomic, strong)UITextField *searchTextField;
@property(nonatomic, strong)UILabel *searchTextLabel;
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSMutableArray *dataArray;

@property (strong, nonatomic) EFSearchRecentView *recentView;
@property (strong, nonatomic) EFRecentSearchItem *recentItem;

@property (assign, nonatomic) NSInteger       pageIndex;
@property (copy, nonatomic)   NSString        *searchKey;
@property (strong, nonatomic) EFSearchResultItem *searchResultItem;

@property (strong, nonatomic) EFSearchTopCell *topView;
@property (strong, nonatomic) UIView *topBackView;
@property (strong, nonatomic) UITableView *topTableView;
@property (strong, nonatomic) NSMutableArray *topArray;
@property (assign, nonatomic) NSInteger topType;//1:价格 2：销量 3：分类 4 促销

@end

@implementation EFSearchViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.dataArray = [NSMutableArray array];
        self.topArray = [NSMutableArray array];
        self.pageIndex = 1;
        self.searchKey = @"";
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightButton setTitle:@"取消" forState:UIControlStateNormal];
    [rightButton setTitleColor:kBlack333 forState:UIControlStateNormal];
    rightButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [rightButton addTarget:self action:@selector(cancelTypeAddress)
          forControlEvents:UIControlEventTouchUpInside];
    rightButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
    [rightButton sizeToFit];
    rightButton.hidden = NO;
    
    self.navigationItem.rightBarButtonItem= [[UIBarButtonItem alloc] initWithCustomView:rightButton];

    UIView* titleView = [[UIView alloc] initWithFrame:ccr(0, 0, kScreenWidth - 113, 28)];
    titleView.backgroundColor = RGBCOLOR(0xF5F9F9);
    //add textField
    [titleView addSubview:self.searchTextField];
    
    self.navigationItem.titleView = titleView;

    [self initView];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
   }

- (void)cancelTypeAddress{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initView{
    [self.view addSubview:self.topView];
    [self.view addSubview:self.tableView];
    self.tableView.top = self.topView.bottom;
    self.topView.hidden = YES;
    self.tableView.hidden = YES;
    //弹出最近搜索页面
    [self.view addSubview:self.recentView];

}



#pragma mark - TableView Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == self.topTableView) {
        return self.topArray.count;
    }
    return [self.dataArray count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.topTableView) {
        return 35;
    }
    return 102;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
    if (tableView == self.tableView) {
        ICTableViewItem *item = self.dataArray[indexPath.row];
        ICTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"search"];
        if (cell == nil){
            cell = [[EFSearchResultCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"search"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        [(EFSearchResultCell *)cell setObject:(EFSepecialItem *)item];
        return cell;
    }else if(tableView == self.topTableView){
        EFTopTypeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"top"];
        if (cell == nil) {
            cell = [[EFTopTypeCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"top"];
        }
        if (self.topType == 3) {
            NSMutableArray *titleArray = [NSMutableArray array];
            for (EFSearchCategoryItem *item in self.topArray) {
                [titleArray addObject:item.catName];
            }
            [cell setContent:[titleArray objectAtIndex:indexPath.row]];
        }else{
            [cell setContent:[self.topArray objectAtIndex:indexPath.row]];
        }
        return cell;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   // ICTableViewItem *item = self.dataArray[indexPath.row];
    if (tableView == self.topTableView) {
        
        if (self.topType == 1) {
            NSString *title = [self.topArray objectAtIndex:indexPath.row];
            if ([title isEqualToString:@"从低到高"]) {
                [self showHUD];
                 [self searchInfor:self.searchKey pageIndex:1 orderByPrice:1 orderBySellQty:0 category:0 isSale:0];
            }else if([title isEqualToString:@"从高到低"]){
                [self showHUD];
            [self searchInfor:self.searchKey pageIndex:1 orderByPrice:2 orderBySellQty:0 category:0 isSale:0];}
           
        }else if(self.topType == 2){
            NSString *title = [self.topArray objectAtIndex:indexPath.row];
            if ([title isEqualToString:@"从低到高"]) {
                [self showHUD];
                [self searchInfor:self.searchKey pageIndex:1 orderByPrice:0 orderBySellQty:1 category:0 isSale:0];
            }else if([title isEqualToString:@"从高到低"]){
                [self showHUD];
                [self searchInfor:self.searchKey pageIndex:1 orderByPrice:0 orderBySellQty:2 category:0 isSale:0];}
        }else if(self.topType == 3){
            //self.topArray 存储的是 EFSearchCategoryItem
            EFSearchCategoryItem *cItem = [self.topArray objectAtIndex:indexPath.row];
            NSNumber *nId = cItem.catId;
            [self showHUD];
            [self searchInfor:self.searchKey pageIndex:1 orderByPrice:0 orderBySellQty:2 category:nId.integerValue isSale:0];
        }
    }else if(tableView == self.tableView){
        EFSepecialItem *item = self.dataArray[indexPath.row];
        //跳转商品详情页
        EFGoodsDetailViewController *vc = [[EFGoodsDetailViewController alloc] initWithProductId:item.id wareHouseId:item.warehouse_id];
        [ICNavigator pushViewController:vc animated:YES];
    }
    
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 32, kScreenWidth, kScreenHeight - kStatusBarHeight - 32)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor clearColor];
    }
    return _tableView;
}

- (UIView *)topBackView{
    if (!_topBackView) {
        _topBackView = [[UIView alloc] initWithFrame:CGRectMake(0, 32, kScreenWidth, kScreenHeight - kStatusBarHeight - 32)];
        _topBackView.backgroundColor = [UIColor blackColor];
        _topBackView.alpha = 0.6;
        [_topBackView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(topDisappear)]];
        _topBackView.userInteractionEnabled = YES;
    }
    return _topBackView;
}

- (UITableView *)topTableView{
    if (!_topTableView) {
        _topTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 32, kScreenWidth, kScreenHeight - kStatusBarHeight - 32)];
        _topTableView.delegate = self;
        _topTableView.dataSource = self;
        _topTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _topTableView.backgroundColor = [UIColor whiteColor];
    }
    return _topTableView;
}

- (EFSearchRecentView *)recentView{
    if(!_recentView){
        _recentView = [[EFSearchRecentView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        __weak typeof(self) weakSelf = self;
        _recentView.btnBlock = ^(NSString *str){
            [weakSelf showHUD];
             [weakSelf searchInfor:str pageIndex:weakSelf.pageIndex orderByPrice:0 orderBySellQty:0 category:0 isSale:0];
            if (_recentView != nil) {
                 [_recentView removeFromSuperview];
            }
        };
    }
    return _recentView;
}

- (UITextField *)searchTextField{
    if (!_searchTextField) {
        _searchTextField = [[UITextField alloc] initWithFrame:ccr(-20, 0, kScreenWidth - 113, 28)];
        _searchTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _searchTextField.font = FONT(15.f);
        _searchTextField.backgroundColor = RGBCOLOR(0xF5F9F9);
        _searchTextField.textColor = RGBCOLOR(0x333333);
        //_textField.textAlignment = NSTextAlignmentCenter;
        _searchTextField.returnKeyType = UIReturnKeySearch;
        _searchTextField.borderStyle = UITextBorderStyleNone;
        _searchTextField.layer.cornerRadius = 2.0;
        _searchTextField.delegate = self;
        [_searchTextField addTarget:self action:@selector(textFieldValueChanged:) forControlEvents:UIControlEventEditingChanged];
    }
    return _searchTextField;
}

#pragma mark --UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    
}

- (void)textFieldValueChanged:(UITextField*)textField
{
    if (self.recentView != nil) {
        [self.recentView removeFromSuperview];
    }
    self.pageIndex = 1;
    [self showHUD];
    [self searchInfor:textField.text pageIndex:self.pageIndex orderByPrice:0 orderBySellQty:0 category:0 isSale:0];
}

- (void)searchInfor:(NSString *)key pageIndex:(NSInteger)index orderByPrice:(NSInteger)orderByPrice orderBySellQty:(NSInteger)orderBySellQty category:(NSInteger)category isSale:(NSInteger)isSale{
    self.searchKey = key;
    if (self.topTableView != nil) {
        [self.topTableView removeFromSuperview];
    }
    if (key.length > 0) {
        self.pageIndex = index;
        [APP_CONTEXT.net searchResultKey:key page:self.pageIndex orderByPrice:orderByPrice orderBySellQty:orderBySellQty category:category isSale:isSale OnComplete:^(NSInteger code, NSDictionary *info, NSString *message) {
            self.HUD.hidden = YES;
            //解析返回数据
            if (code != 0) {
                [[iToast makeText:message] show];
            }else{
                self.searchResultItem = [EFSearchResultItem yy_modelWithDictionary:info];
                self.dataArray = self.searchResultItem.list;
                self.topView.hidden = NO;
                [self.topView setObject:self.searchResultItem.categoryList];
                if (self.dataArray.count == 0) {
                    self.tableView.hidden = YES;
                    [self showEmptyImageView:@"bg_icon_search" message:@"没有找到任何相关信息"];
                }else{
                    [self.tableView reloadData];
                    self.tableView.hidden = NO;
                    [self hideEmptyView];
                    if (self.topTableView != nil) {
                        if (self.topBackView != nil) {
                            [self.topBackView removeFromSuperview];
                        }
                        if (self.topTableView != nil) {
                            [self.topTableView removeFromSuperview];
                        }
                    }
                }
            }
        }];
    }
}

- (EFSearchTopCell *)topView{
    if (!_topView) {
        _topView = [[EFSearchTopCell alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 32)];
    }
    __weak typeof(self) weakSelf = self;
    _topView.type = ^(NSMutableArray *array,NSInteger type){
        //根据传过来的参数 创建view
        if (weakSelf.topBackView != nil) {
            [weakSelf.topBackView removeFromSuperview];
        }
        if (weakSelf.topTableView != nil) {
            [weakSelf.topTableView removeFromSuperview];
        }
        if (type == 4) {
            //直接刷新tableView
            //TODO
            [weakSelf showHUD];
            [weakSelf searchInfor:weakSelf.searchKey pageIndex:1 orderByPrice:0 orderBySellQty:0 category:0 isSale:1];
        }else{
            
            weakSelf.topArray = array;
            [weakSelf.view addSubview:weakSelf.topBackView];
            [weakSelf.view addSubview:weakSelf.topTableView];
            weakSelf.topTableView.height = weakSelf.topArray.count * 35;
            [weakSelf.topTableView reloadData];
            weakSelf.topType = type;

        }
        };
    return _topView;
}

- (void)topDisappear{
    if (self.topBackView != nil) {
        [self.topBackView removeFromSuperview];
    }
    if (self.topTableView != nil) {
        [self.topTableView removeFromSuperview];
    }
}

@end
